<template>
  <div class="cut-picture">
    <el-button type="text" size="mini" @click="toggleShow">更换头像</el-button>
    <my-upload
      v-model="show"
      field="file"
      :width="200"
      :height="200"
      :url="avatarUploadUrl"
      :preview="'图形展示'"
      img-format="jpg"
      @crop-upload-success="cropUploadSuccess"
      @crop-upload-fail="cropUploadFail"
    />
  </div>
</template>

<script>
import myUpload from 'vue-image-crop-upload/upload-2.vue'
import { updateAvatar } from '@/api/user'
export default {
  name: 'UpdateAvatar',
  components: {
    'my-upload': myUpload
  },
  props: {

  },
  data() {
    return {
      show: false,
      avatarUploadUrl: process.env.VUE_APP_BASE_API + 'register/uploadAvatar'
    }
  },
  mounted() {
  },
  methods: {
    toggleShow() {
      this.show = !this.show
    },
    cropUploadSuccess(jsonData, field) {
      // 服务器返回成功
      if (jsonData.success) {
        // 新的名称- jsonData.data
        updateAvatar({ avatar: jsonData.data }).then(
          (response) => {
            this.$store.dispatch('user/getInfo')
          },
          (error) => {
            this.$message.error(error.message)
          }
        )
      } else {
        this.$message.error(jsonData.errMessage)
      }
    },
    cropUploadFail(status, field) {
      // 服务器返回失败
      this.$message.error(status)
    }
  }
}
</script>
<style lang="scss" scoped>
  .avatar {
    border-radius: 50%;
    width: 100px;
    height: 100px;
  }
  .avatar:hover{
    cursor: pointer;
  }
</style>
